package com.xiaozhichao.databafflesys.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaozhichao.databafflesys.common.domain.BaffleUserChange;
import com.xiaozhichao.databafflesys.common.domain.ExceptionEnums;
import com.xiaozhichao.databafflesys.common.domain.ResultVo;
import com.xiaozhichao.databafflesys.repository.model.BaffleUser;
import com.xiaozhichao.databafflesys.repository.service.BaffleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaozhichao
 * @since 2021-03-26
 */
@Controller
public class BaffleUserController {

    @Autowired
    BaffleUserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public ResultVo login(@RequestBody BaffleUser entry){
        if(Objects.isNull(entry)){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"登录失败");
        }
        QueryWrapper<BaffleUser> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(true,BaffleUser::getName,entry.getName())
                .eq(true,BaffleUser::getPassword,entry.getPassword());
        BaffleUser one = userService.getOne(wrapper);
        if(Objects.isNull(one)){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"用户名密码错误");
        }
        return ResultVo.getResult(ExceptionEnums.SUCCESS);
    }

    @RequestMapping("/changePassword")
    @ResponseBody
    public ResultVo changePassword(@RequestBody BaffleUserChange entry){
        if(Objects.isNull(entry)){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"修改失败");
        }
        QueryWrapper<BaffleUser> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(true,BaffleUser::getName,entry.getName())
                .eq(true,BaffleUser::getPassword,entry.getPassword());
        BaffleUser one = userService.getOne(wrapper);
        if(Objects.isNull(one)){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"原密码错误");
        }
        one.setPassword(entry.getNewPassword());
        userService.saveOrUpdate(one);
        return ResultVo.getResult(ExceptionEnums.SUCCESS);
    }

    @RequestMapping("/logout")
    public String index(){
        return "redirect:/";
    }

}

